using System.Text;
using System.Threading.Tasks;
using System.Net;
using System;
using System.Net.Sockets;
public abstract class IHttp{    
    private Socket ser;
    protected DistNode dist=new DistNode();
    public void Start(EndPoint point){
        ser=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        ser.Bind(point);
        ser.Listen(10);
        System.Console.WriteLine("服务正在启动....");
        while(true){
            Socket cli=ser.Accept();
             
            HandleRequest(cli);
        }
    }
    public  async void HandleRequest(Socket s){  
        byte[] msg=new byte[512];
        int len= s.Receive(msg);
        await  Task.Run(new System.Action(()=>{
            
            System.Console.WriteLine("收到请求",s.AddressFamily.ToString());
        
            string reqStr=Encoding.UTF8.GetString(msg);
            ServerHttp(GetRequest(reqStr),new HttpResponse(s));
        }));

    }
    public HttpRequest GetRequest(string str) {
        string[] https=str.Split("\r\n");

        HttpRequest req=new HttpRequest();
        if(https[0].Split(" ").Length<2)return req;
        req.URL=https[0].Split(" ")[1];
        req.Put("Method",req.URL);
        for(int i=1;i<https.Length;i++){
            string[] heads=https[i].Split(":");
            //System.Console.WriteLine(https[i]);
            if(heads.Length<2)
                continue;
            req.Put(heads[0],heads[1]);
        }
        
        return req;
    }
    public abstract void ServerHttp(HttpRequest req,HttpResponse resp);
    
}